
package com.gamatechno.solodestinationnew;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.content.res.Configuration;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.SearchView;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.facebook.HttpMethod;
import com.facebook.LoggingBehavior;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.gamatechno.solodestinationnew.adapter.AdapterNavMenu;
import com.gamatechno.solodestinationnew.entity.E_Forecast;
import com.gamatechno.solodestinationnew.helper.JSONHelper;
import com.gamatechno.solodestinationnew.utils.CircleTransform;
import com.gamatechno.solodestinationnew.utils.Utils;
import com.gamatechno.solodestinationnew.utils.Webservice;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.LocationSource.OnLocationChangedListener;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.squareup.picasso.Picasso;

/**
 * release key : vTpnccLJ+maRZlry/YaN+jUuhI4=
 * <p>
 * debug :
 * </p>
 * D6KglwkneBiZIyPQVyhOrrIzTno=
 * 
 * @author pratama
 */
public class MainActivity extends BaseActivity implements OnClickListener,
        OnConnectionFailedListener, ConnectionCallbacks, OnItemClickListener,
        OnLocationChangedListener {
    private static final String TAG = "MAINACTIVITY";

    // untuk location
    private LocationClient mLocationClient;
    private boolean locationFound;
    private Location location;

    // final CONSTANT
    public static final int CATEGORY_KULINER = 1;
    public static final int CATEGORY_HOTEL = 2;
    public static final int CATEGORY_TOURISM = 3;
    public static final int CATEGORY_SHOPPING = 4;
    public static final int CATEGORY_HANDYCRAFT = 5;

    // menu
    private LinearLayout menuKuliner, menuHotel, menuWisata, menuEvent, menuBelanja, menuKerajinan,
            menuBagikanFoto, menuGallery, menuInfoLalin;

    // img for flipping
    private int[] imgFlipp = {
            R.drawable.img_menu_flip1,
            R.drawable.img_menu_flip2,
            R.drawable.img_menu_flip3,
    };

    // nav drawer
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;

    private ListView lvNavDrawer;
    private AdapterNavMenu adapterNavDrawer;

    private int[] menuNavIcon = {
            R.drawable.ic_favorite,
            R.drawable.ic_cekin,
            R.drawable.ic_notifikasi,
            R.drawable.ic_pengaturan
    };

    // vlipper
    private ViewFlipper vlipper;
    private LinearLayout vlipperForecast;
    private LayoutInflater inflater;
    private TextView txtCity, txtTemp, txtDate;
    private List<E_Forecast> listForecast;

    // user view
    private LinearLayout viewUser;
    private RelativeLayout viewConnect;

    // gcm
    private HashMap<String, String> params;
    private static final String SENDER_ID_GCM = "204153616086";
    private GoogleCloudMessaging gcm;
    private String gcm_id;

    // login fb
    private Button btn_login_fb, btn_logout;
    private ImageView thumbUser;
    private TextView txtUser;
    private Session.StatusCallback statusCallback = new SessionStatusCallback();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        overridePendingTransition(R.anim.activity_open_translate, R.anim.activity_close_scale);

        inflater = LayoutInflater.from(this);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mLocationClient = new LocationClient(this, this, this);

        viewUser = (LinearLayout) findViewById(R.id.view_user);
        viewConnect = (RelativeLayout) findViewById(R.id.view_connect);
        vlipper = (ViewFlipper) findViewById(R.id.flipper);
        vlipperForecast = (LinearLayout) findViewById(R.id.flipper_forecast);
        menuKuliner = (LinearLayout) findViewById(R.id.menu_kuliner);
        menuHotel = (LinearLayout) findViewById(R.id.menu_hotel);
        menuWisata = (LinearLayout) findViewById(R.id.menu_wisata);
        menuEvent = (LinearLayout) findViewById(R.id.menu_event);
        menuBelanja = (LinearLayout) findViewById(R.id.menu_belanja);
        menuKerajinan = (LinearLayout) findViewById(R.id.menu_kerajinan);
        menuBagikanFoto = (LinearLayout) findViewById(R.id.menu_bagikan_foto);
        menuGallery = (LinearLayout) findViewById(R.id.menu_gallery);
        menuInfoLalin = (LinearLayout) findViewById(R.id.menu_info_lalin);
        lvNavDrawer = (ListView) findViewById(R.id.lv_nav_drawer);
        txtCity = (TextView) findViewById(R.id.city);
        txtTemp = (TextView) findViewById(R.id.temp);
        txtDate = (TextView) findViewById(R.id.date);
        btn_login_fb = (Button) findViewById(R.id.btn_connect);
        btn_logout = (Button) findViewById(R.id.btn_logout);
        txtUser = (TextView) findViewById(R.id.user_name);
        thumbUser = (ImageView) findViewById(R.id.thumb_user);

        Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
        Session session = Session.getActiveSession();

        if (session == null) {

            if (savedInstanceState != null)
                session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
            if (session == null)
                session = new Session(this);

            Session.setActiveSession(session);
            if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
                session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
                // getUserData(session);
            }
        }
        updateState();

        // title for nav drawer
        String[] menuNav = {
                getResources().getString(R.string.txt_drawer_favorie),
                getResources().getString(R.string.txt_drawer_jurnal),
                getResources().getString(R.string.txt_drawer_notifikasi),
                getResources().getString(R.string.txt_drawer_pengaturan)
        };

        adapterNavDrawer = new AdapterNavMenu(this, menuNavIcon, menuNav);

        lvNavDrawer.setAdapter(adapterNavDrawer);
        lvNavDrawer.setOnItemClickListener(this);

        // set flipping image
        for (int i = 0; i < imgFlipp.length; i++) {
            ImageView img = new ImageView(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            img.setLayoutParams(params);
            img.setScaleType(ScaleType.CENTER_CROP);
            img.setBackgroundResource(imgFlipp[i]);
            vlipper.addView(img);
        }

        vlipper.setFlipInterval(4000);
        vlipper.startFlipping();
        vlipper.setInAnimation(this, R.anim.anim_vlipper_in);
        vlipper.setOutAnimation(this, R.anim.anim_vlipper_out);

        Date date = Calendar.getInstance().getTime();
        SimpleDateFormat df = new SimpleDateFormat("EEE, d MMM yy", Locale.ENGLISH);

        txtDate.setText("" + df.format(date));

        // nav drawer
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_transparent, R.string.txt_open,
                R.string.txt_close);
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        // get hash for facebook login
        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "com.gamatechno.solodestinationnew",
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Utils.TRACE("MainActivity",
                        "onCreate : keyHash : " + Base64.encodeToString(md.digest(),
                                Base64.DEFAULT));

            }
        } catch (NameNotFoundException e) {
            Utils.TRACE("LoginActivity", "onCreate : " + e.getMessage());

        } catch (NoSuchAlgorithmException e) {
            Utils.TRACE("LoginActivity", "onCreate : " + e.getMessage());
        }

        menuKuliner.setOnClickListener(this);
        menuHotel.setOnClickListener(this);
        menuWisata.setOnClickListener(this);
        menuEvent.setOnClickListener(this);
        menuBelanja.setOnClickListener(this);
        menuKerajinan.setOnClickListener(this);
        menuBagikanFoto.setOnClickListener(this);
        menuGallery.setOnClickListener(this);
        menuInfoLalin.setOnClickListener(this);
        btn_login_fb.setOnClickListener(this);
        btn_logout.setOnClickListener(this);

        getCurrentWeather(Webservice.GET_WEATHER);
        getCurrentForecast(Webservice.GET_FORECAST);

        if (gcm == null)
            gcm = GoogleCloudMessaging.getInstance(this);

        // reg GCM
        new AsyncGCM().execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);

        MenuItem searchItem = menu.findItem(R.id.action_search_news);

        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        return true;
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        overridePendingTransition(R.anim.activity_open_scale, R.anim.activity_close_translate);
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        mLocationClient.connect();
        Session.getActiveSession().addCallback(statusCallback);
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        mLocationClient.disconnect();
        Session.getActiveSession().removeCallback(statusCallback);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        Utils.setLocale(this, Utils.getDataStringFromSP(this, Utils.PREF_BAHASA));
        updateState();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Session session = Session.getActiveSession();
        Session.saveSession(session, outState);
    }

    private void updateState() {
        Session session = Session.getActiveSession();
        if (session.isOpened()) {
            Utils.TRACE("MainActivity", "updateState : User Logged");

            viewUser.setVisibility(View.VISIBLE);
            viewConnect.setVisibility(View.GONE);
            Utils.setDataBooleanToSP(this, Utils.PREF_ISLOGIN, true);
            getUserData(session);
            getUserPicture(session);
        } else {
            Utils.TRACE("MainActivity", "updateState : User Logout, change text to login");
            viewUser.setVisibility(View.GONE);
            viewConnect.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item))
            return true;
        if (item.getItemId() == R.id.action_search) {
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    /**
     * alert dialog untuk instalasi info lalin
     * 
     * @author pratama
     */
    private void showDialogInstall() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);

        dialog.setTitle("Install");
        dialog.setMessage("Apakah anda akan menginstall Info Lalulintas Solo?");
        dialog.setPositiveButton("Install", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri
                        .parse("market://details?id=com.its.infolalinsolo"));
                startActivity(intent);
            }
        });
        dialog.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub

                arg0.cancel();
            }
        });
        dialog.show();
    }

    @Override
    public void onClick(View v) {
        Bundle data = new Bundle();
        if (locationFound) {
            data.putDouble("lat", location.getLatitude());
            data.putDouble("lng", location.getLongitude());
        }
        switch (v.getId()) {
            case R.id.menu_kuliner:
                data.putInt("category", CATEGORY_KULINER);
                if (locationFound)
                    startActivity(new Intent(this, CategoryActivity.class).putExtras(data));
                else {
                    Toast.makeText(this, getResources().getString(R.string.txt_gps_activated),
                            Toast.LENGTH_SHORT).show();
                    showGPS();
                }
                break;
            case R.id.menu_hotel:
                data.putInt("category", CATEGORY_HOTEL);
                if (locationFound)
                    startActivity(new Intent(this, CategoryActivity.class).putExtras(data));
                else {
                    Toast.makeText(this, getResources().getString(R.string.txt_gps_activated),
                            Toast.LENGTH_SHORT).show();
                    showGPS();
                }
                break;
            case R.id.menu_wisata:
                data.putInt("category", CATEGORY_TOURISM);
                if (locationFound)
                    startActivity(new Intent(this, CategoryActivity.class).putExtras(data));
                else {
                    Toast.makeText(this, getResources().getString(R.string.txt_gps_activated),
                            Toast.LENGTH_SHORT).show();
                    showGPS();
                }
                break;
            case R.id.menu_event:
                startActivity(new Intent(this, EventActivity.class));
                break;
            case R.id.menu_belanja:
                data.putInt("category", CATEGORY_SHOPPING);
                if (locationFound)
                    startActivity(new Intent(this, CategoryActivity.class).putExtras(data));
                else {
                    Toast.makeText(this, getResources().getString(R.string.txt_gps_activated),
                            Toast.LENGTH_SHORT).show();
                    showGPS();
                }
                break;
            case R.id.menu_kerajinan:
                data.putInt("category", CATEGORY_HANDYCRAFT);
                if (locationFound)
                    startActivity(new Intent(this, CategoryActivity.class).putExtras(data));
                else {
                    Toast.makeText(this, getResources().getString(R.string.txt_gps_activated),
                            Toast.LENGTH_SHORT).show();
                    showGPS();
                }
                break;
            case R.id.menu_bagikan_foto:
                startActivity(new Intent(this, BagikanFoto.class));
                break;
            case R.id.menu_gallery:
                startActivity(new Intent(this, GalleryActivity.class));
                break;
            case R.id.menu_info_lalin:
                Intent intent;
                PackageManager pm = this.getPackageManager();
                try {
                    intent = pm.getLaunchIntentForPackage("com.its.infolalinsolo");
                    if (intent == null) {
                        Toast.makeText(this, "App Tidak Terinstall", Toast.LENGTH_SHORT)
                                .show();
                        showDialogInstall();
                    }

                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
                    startActivity(intent);
                } catch (Exception e) {
                    Log.d("e", "" + e.getMessage());
                }
                break;
            case R.id.btn_connect:
                Session session = Session.getActiveSession();
                if (!session.isOpened() && !session.isClosed()) {
                    Utils.TRACE("MainActivity", "onClick : session closed");
                    session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
                } else {
                    Utils.TRACE("MainActivity", "onClick : session open");
                    Session.openActiveSession(this, true, statusCallback);
                }
                break;
            case R.id.btn_logout:
                Session sess = Session.getActiveSession();
                if (!sess.isClosed()) {
                    sess.closeAndClearTokenInformation();
                    Toast.makeText(this, "Logout", Toast.LENGTH_SHORT).show();
                    Utils.setDataBooleanToSP(this, Utils.PREF_ISLOGIN, false);
                }
                break;
        }

    }

    private void getUserPicture(Session session) {
        Bundle params = new Bundle();
        params.putBoolean("redirect", false);
        params.putString("type", "large");

        new com.facebook.Request(session, "/me/picture", params, HttpMethod.GET,
                new com.facebook.Request.Callback() {

                    @Override
                    public void onCompleted(com.facebook.Response response) {
                        JSONObject jsonObject = null;
                        try {

                            jsonObject = new JSONObject(
                                    response.getGraphObject()
                                            .getInnerJSONObject()
                                            .toString());
                            JSONObject obj = jsonObject.getJSONObject("data");

                            // user.setImageProfilURL(obj.getString("url"));
                            //
                            Picasso.with(MainActivity.this).load(obj.getString("url"))
                                    .transform(new
                                            CircleTransform()).into(thumbUser);

                        } catch (JSONException e) {
                            Utils.TRACE(
                                    "MenuUtamaActivity.getUserPicture(...).new Callback() {...}",
                                    "onCompleted : " + e.getMessage());
                        }
                    }

                }).executeAsync();
    }

    /**
     * get data user fb
     * 
     * @param session
     */
    private void getUserData(Session session) {
        new com.facebook.Request(session, "/me", null, HttpMethod.GET,
                new com.facebook.Request.Callback() {

                    @Override
                    public void onCompleted(com.facebook.Response response) {
                        JSONObject jsonObject = null;
                        try {

                            jsonObject = new JSONObject(
                                    response.getGraphObject()
                                            .getInnerJSONObject()
                                            .toString());
                            Utils.TRACE("MainActivity.getUserData(...).new Callback() {...}",
                                    "onCompleted : " + jsonObject.toString());
                            Utils.setDataStringToSP(MainActivity.this, Utils.PREF_FB_ID,
                                    jsonObject.getString("id"));
                            txtUser.setText(jsonObject.getString("name"));
                            Utils.setDataStringToSP(MainActivity.this, Utils.PREF_USERNAME,
                                    jsonObject.getString("name"));
                        } catch (JSONException e) {
                            Utils.TRACE("MenuUtamaActivity.getUserData(...).new Callback() {...}",
                                    "onCompleted : " + e.getMessage());
                        }
                    }
                }).executeAsync();
    }

    /**
     * generate forecast view,, add into linearlayout
     * 
     * @param listForecast List of Forecast object
     */
    private void generateForecast(List<E_Forecast> listForecast) {
        for (E_Forecast forecast : listForecast) {
            View view = inflater.inflate(R.layout.item_forecast, null);

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            params.setMargins(25, 0, 0, 0);
            view.setLayoutParams(params);

            final TextView date = (TextView) view.findViewById(R.id.date_forecast);
            final TextView status = (TextView) view.findViewById(R.id.status_forecast);
            final TextView temp = (TextView) view.findViewById(R.id.temp_forecast);
            final ImageView img = (ImageView) view.findViewById(R.id.thumb_forecast);

            date.setText(forecast.getDate());
            status.setText(forecast.getStatus());
            temp.setText(forecast.getTemp() + " " + (char) 0x00B0 + "C");
            ImageLoader.getInstance().displayImage(forecast.getIcon(), img,
                    BaseApplication.getDisplayImageOptions());

            vlipperForecast.addView(view);
        }
    }

    /**
     * get Forecast
     * 
     * @param URL
     */
    private void getCurrentForecast(String URL) {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
                URL,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        // Utils.TRACE("MainActivity.getCurrentForecast(...).new Listener() {...}",
                        // "getCurrentForecast : " + response.toString());

                        try {
                            listForecast = JSONHelper.getForecast(response.getJSONArray("list"));
                            generateForecast(listForecast);

                        } catch (JSONException e) {
                            Utils.TRACE(
                                    "MainActivity.getCurrentForecast(...).new Listener() {...}",
                                    "onResponse : " + e.getMessage());

                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Utils.TRACE(
                                "MainActivity.getCurrentForecast(...).new ErrorListener() {...}",
                                "getCurrentForecast : " + error);
                        Utils.showVolleyError(MainActivity.this, error);
                    }
                });
        BaseApplication.getInstance().addToRequestQueue(request, TAG);
    }

    /**
     * query current weather from API
     * 
     * @param URL
     */
    private void getCurrentWeather(String URL) {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, URL,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        // Utils.TRACE("MainActivity.getCurrentWeather",
                        // "getCurrentWeather : " + response.toString());
                        try {
                            JSONObject obj = response.getJSONObject("main");
                            if (obj.has("temp"))
                                txtTemp.setText("" + obj.getInt("temp") + " " + (char) 0x00B0 + "C");
                        } catch (JSONException e) {
                            Utils.TRACE("MainActivity.getCurrentWeather(...).new Listener() {...}",
                                    "onResponse : " + e.getMessage());
                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        txtTemp.setText("Failed");
                        Utils.TRACE(
                                "MainActivity.getCurrentWeather(...).new ErrorListener() {...}",
                                "getCurrentWeather : " + error);
                        Utils.showVolleyError(MainActivity.this, error);
                    }
                });
        txtTemp.setText("Loading...");
        BaseApplication.getInstance().addToRequestQueue(request, TAG);
    }

    private void sentRegisterGCM(String URL) {
        StringRequest request = new StringRequest(Request.Method.POST,
                URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Utils.TRACE("MainActivity.sentRegisterGCM(...).new StringRequest() {...}",
                                "sentRegisterGCM : " + response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Utils.TRACE("MainActivity.sentRegisterGCM(...).new StringRequest() {...}",
                                "sentRegisterGCM : " + error.getMessage());
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                params = new HashMap<String, String>();
                params.put("method", "reg");
                params.put("format", "json");
                params.put("reg", "" + gcm_id);
                return params;
            }
        };
        BaseApplication.getInstance().addToRequestQueue(request, TAG);
    }

    // ASYNC REGISTER GCM
    private class AsyncGCM extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            try {
                gcm_id = gcm.register(SENDER_ID_GCM);
                Utils.TRACE("MainActivity.AsyncGCM", "doInBackground : GCM registered -> " + gcm_id);
            } catch (Exception e) {
                Utils.TRACE("MainActivity.AsyncGCM", "error " + e.getMessage());
            }
            return null;
        }

        // kirim gcm ke server
        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            sentRegisterGCM(Webservice.REGISTER_GCM);
        }

    }

    @Override
    public void onConnected(Bundle connectionHint) {
        if (mLocationClient.isConnected())
        {
            location = mLocationClient.getLastLocation();
            if (location != null) {
                locationFound = true;
                Utils.TRACE("MainActivity", "onConnected : " + location.getLatitude());
                Utils.TRACE("MainActivity", "onConnected : location found");
            } else {
                Utils.TRACE("MainActivity", "onConnected : location not found");
            }
        }
    }

    @Override
    public void onDisconnected() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();
        if (result.hasResolution()) {
            Toast.makeText(this, "Result Has Resolution", Toast.LENGTH_LONG).show();
            try {
                result.startResolutionForResult(this, 1);
            } catch (IntentSender.SendIntentException e) {
                Log.d("error", "" + e.getMessage());
            }
        } else {
            Toast.makeText(this, "No Resolution", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
        switch (pos) {
            case 0:
                startActivity(new Intent(this, FavoritedActivity.class));
                break;
            case 1:
                startActivity(new Intent(this, JournalActivity.class));
                break;
            case 2:
                startActivity(new Intent(this, NotificationActivity.class));
                break;
            case 3:
                startActivity(new Intent(this, SettingActivity.class));
                finish();
                break;
        }
    }

    private class SessionStatusCallback implements Session.StatusCallback {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
            updateState();
        }
    }

    private void showGPS() {
        Intent i = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivityForResult(i, 1);
    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
    }
}
